class MyBlockingQueue {
    private int[] elem;
    private int size;
    private int head;
    private int tail;

    Object locker = new Object();

    public MyBlockingQueue(int capacity) {
        elem = new int[capacity];
    }

    public void put(int x) throws InterruptedException {
        synchronized (locker) {
            while (size == elem.length) {
                locker.wait();
            }
            elem[tail] = x;
            tail++;
            if (tail == elem.length) {
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }

    public int take() throws InterruptedException {
        synchronized (locker) {
            while (size == 0) {
                locker.wait();
            }
            int x = elem[head];
            head++;
            if (head == elem.length) {
                head = 0;
            }
            size--;
            locker.notify();
            return x;
        }
    }
}

public class Demo3 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue = new MyBlockingQueue(3);
        Thread t1 = new Thread(() -> {
           int n = 0;
           while(true) {
               try {
                   queue.put(n);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
               n++;
           }
        });

        Thread t2 = new Thread(() -> {
           int n = 0;
           while(true) {
               try {
                   queue.take();
                   System.out.println("消费元素" + n);
                   n++;
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

       /* t1.start();
        t2.start();*/

/*        for(int i = 0; i < 4; i++) {
            queue.put(i);
            queue.take();
            System.out.println(i);
        }*/
    }
}
